# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1625': {  # loki 支付宝 2.9% 10--10000
        'API_KEY': 'iJElkLCG157qfxhZLfn1MQaGKudbHdLJ',
        'gateway': 'http://114.55.202.198/lefu/api/pay/doPay.pay',
        'query_gateway': 'http://114.55.202.198/lefu/api/pay/doQuery.pay',
        # 'service': '11434',
        'service': '11266'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_service_type(mch_id):
    return APP_CONF[mch_id]['service']


def _get_pay_type(service):
    # 支付宝-WAP 2001
    if service == 'alipay':
        return '2001'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += str(key)
    _LOGGER.info("lefuv2pay notify sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_notify_sign(parameter, key):
    s = 'fee={}&orderIdCp={}&version={}&{}'.format(
        parameter['fee'], parameter['orderIdCp'], parameter['version'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("lefuv2pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    """ 创建订单 """
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('cpId', app_id),
        ('serviceId', _get_service_type(app_id)),  # 服务id
        ('payType', _get_pay_type(service)),
        ('fee', str(int(pay_amount * 100))),
        ('subject', 'charge'),  # 商品名
        ('description', 'charge'),  # 商品说明
        ('orderIdCp', str(pay.id)),
        ('notifyUrl', '{}/pay/api/{}/lefuv2pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('callbackUrl', '{}/pay/api/{}/lefuv2pay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('timestamp', int(round(time.time() * 1000))),
        ('ip', _get_device_ip(info)),
        ('version', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lefuv2pay create  data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info("lefuv2pay create  response: %s", response.text)
    return {'charge_info': json.loads(response.text)['payUrl']}


# SUCCESS
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("lefuv2pay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderIdCp']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('lefuv2pay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('lefuv2pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = str(data.get('linkId', ''))
    total_fee = float(data['fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0' and total_fee > 0.0:
        _LOGGER.info('lefuv2pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('cpId', app_id),
        ('orderIdCp', str(pay_id)),
        ('timestamp', int(round(time.time() * 1000))),
        ('version', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lefuv2pay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info("lefuv2pay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['data']['payResult'])
        trade_no = str(data['data'].get('linkId', ''))
        total_fee = float(data['data']['fee']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '0':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('lefuv2pay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('lefuv2pay data error, status_code: %s', response.status_code)
